﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PPIDataAccess.General
{
    public class ConfigReader
    {
        private static volatile ConfigReader _instance = null;
        public static ConfigReader GetInstance()
        {
            if (_instance == null)
            {
                lock (typeof(ConfigReader))
                {
                    if (_instance == null)
                    {
                        _instance = new ConfigReader();
                    }
                }
            }
            return _instance;
        }

        public const string K_APPPATH = "C:\\PolePosition\\Poleposition.config";
        protected ConfigReader()
        {
            //Check the existing file.
            if (!File.Exists(K_APPPATH))
            {
                ConfigFile();
            }

        }

        private static void ConfigFile()
        {

            FileStream fs = null;
            StreamWriter writer = null;
            FileInfo f = null;
            try
            {
                fs = File.Open(K_APPPATH, FileMode.Create);
                writer = new StreamWriter(fs);
                writer.WriteLine("APPLICATION:BETA");
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                writer.Close();
                fs.Close();
            }
        }

        public string GetConnectionString()
        {
            StreamReader fr = new StreamReader(K_APPPATH);
            string line = "";
            try
            {
                line = fr.ReadLine();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                fr.Close();
            }
            
            
            if (line.IndexOf(':') > -1)
            {
                string word = line.Split(':')[1];

                if (word == "PRODUCTIVE_PPI")
                    return "Data Source=sql2k509.discountasp.net;Initial Catalog=SQL2005_390264_devpoleposi;Persist Security Info=True;User ID=SQL2005_390264_devpoleposi_user;PWD=password";
                else
                {
                    if (word != "BETA")
                        ConfigFile();
                    return "Data Source=sql2k509.discountasp.net;Initial Catalog=SQL2005_390264_beta;Persist Security Info=True;User ID=SQL2005_390264_beta_user;PWD=password";
                }
            }
            else
            {
                ConfigFile();
                return "Data Source=sql2k509.discountasp.net;Initial Catalog=SQL2005_390264_beta;Persist Security Info=True;User ID=SQL2005_390264_beta_user;PWD=password";
            }




        }

    }
}
